package org.lab.mtga.core.web;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Calendar;

import javax.persistence.EntityManager;

import org.lab.mtga.core.jpa.EntityManagerProvider;
import org.lab.mtga.core.model.Card;
import org.lab.mtga.core.model.ParseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MagicCardCrawler implements Runnable {

	private static final Logger LOG = LoggerFactory.getLogger(MagicCardCrawler.class);

	private final Card card;
	private final EntityManagerProvider entityManagerProvider;

	public MagicCardCrawler(Card card, EntityManagerProvider entityManagerProvider) {
		this.card = card;
		this.entityManagerProvider = entityManagerProvider;
	}

	@Override
	public void run() {
		try {
			LOG.debug("Scanning card {}", card.getName());
			card.setScanned(Calendar.getInstance().getTime());
			String urlString = "http://magiccards.info/query?q=" + URLEncoder.encode(card.getName(), "UTF8") + "&v=card&s=cname";
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();
			InputStream inputStream = connection.getInputStream();
			MagicCardsParser parser = new MagicCardsParser();
			Card readed = parser.parse(inputStream);
			inputStream.close();
			EntityManager entityManager = entityManagerProvider.get();
			entityManager.getTransaction().begin();
			card.setTypes(readed.getTypes());
			card.setText(readed.getText());
			card.setExternalImageUrl(readed.getExternalImageUrl());
			card.setParseResult(ParseResult.Success);
			card.setCmcCount(readed.getCmcCount());
			card.setCmcString(readed.getCmcString());
			card.setLoyalty(readed.getLoyalty());
			card.setPower(readed.getPower());
			card.setToughness(readed.getToughness());
			card.setSubtypes(readed.getSubtypes());
			entityManager.merge(card);
			entityManager.getTransaction().commit();
		} catch (Exception ex) {
			LOG.error(ex.getMessage(), ex);
			card.setParseResult(ParseResult.Error);
		}
	}
}
